import { TableHeader } from './table-header';
import { TableBody } from './table-body';
import { getUniquePersons } from '../../utils/helper';

/**
 * 甘特表格组件
 * 统一管理整个甘特图的表格渲染
 */
export class GanttTable {
  private zr: any;
  private schedules: PersonSchedule[];
  private chartState: ChartState;
  private tableHeader: TableHeader;
  private tableBody: TableBody;

  constructor(zr: any, schedules: PersonSchedule[], chartState: ChartState) {
    this.zr = zr;
    this.schedules = schedules;
    this.chartState = chartState;

    // 初始化表格组件
    this.tableHeader = new TableHeader(zr, chartState);
    this.tableBody = new TableBody(zr, schedules, chartState);
  }

  /**
   * 渲染整个表格
   */
  render() {
    // 清空画布
    this.zr.clear();

    // 渲染表格头部（时间轴）
    this.tableHeader.render();

    // 渲染表格主体（人员行和排班数据）
    this.tableBody.render();
  }

  /**
   * 更新数据并重新渲染
   */
  update(schedules: PersonSchedule[], chartState: ChartState) {
    this.schedules = schedules;
    this.chartState = chartState;

    // 更新子组件
    this.tableHeader.update(chartState);
    this.tableBody.update(schedules, chartState);
  }

  /**
   * 设置行重排序回调
   */
  setRowReorderCallback(callback: RowReorderCallback) {
    this.tableBody.setRowReorderCallback(callback);
  }

  /**
   * 设置当前操作组
   */
  setCurrentGroup(group: any) {
    this.tableBody.setCurrentGroup(group);
  }

  /**
   * 获取表格尺寸信息
   */
  getTableDimensions() {
    const uniquePersons = getUniquePersons(this.schedules);
    const { responsiveConfig } = this.chartState;

    return {
      // 表格总宽度
      totalWidth: this.chartState.canvasWidth,
      // 表格总高度
      totalHeight: this.chartState.canvasHeight,
      // 人员列宽度
      personColumnWidth: responsiveConfig.personColumnWidth,
      // 时间列宽度
      timeColumnWidth: this.chartState.canvasWidth - responsiveConfig.personColumnWidth,
      // 行高度
      // +1 for border
      rowHeight: responsiveConfig.barHeight + 1,
      // 表头高度
      headerHeight: responsiveConfig.timeScaleHeight,
      // 总行数
      totalRows: uniquePersons.length,
    };
  }
}
